package com.rocketmq.base.example.order;

import com.rocketmq.base.example.Const;
import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.apache.rocketmq.client.producer.MessageQueueSelector;
import org.apache.rocketmq.common.message.Message;
import org.apache.rocketmq.common.message.MessageQueue;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @Auther: tianchao
 * @Date: 2021/9/2 15:59
 * @Description:
 */
public class Producer {
    public static void main(String[] args) throws Exception {
        DefaultMQProducer defaultMQProducer = new DefaultMQProducer("my_order_producer_group_name");
        defaultMQProducer.setNamesrvAddr(Const.nameServer);
        defaultMQProducer.start();
        List<ProductOrder> orders = getOrders();
        for (ProductOrder order : orders) {
            Message message = new Message("OrderTopic","TAG-ORDER",order.toString().getBytes());
            System.out.println("发送钱: "+ order.toString());
            TimeUnit.SECONDS.sleep(1);
            defaultMQProducer.send(message, new MessageQueueSelector() {
                @Override
                public MessageQueue select(List<MessageQueue> mqs, Message msg, Object arg) {
                    System.out.println("共有多少队列:" + mqs.size());
                    System.out.println("订单id:" + arg);
                    Integer i = (Integer) arg;
                    return mqs.get(i%mqs.size());
                }
            },order.getId());
        }
        defaultMQProducer.shutdown();
    }
    public static List<ProductOrder> getOrders(){
        List<ProductOrder> orders = new ArrayList<>();
        orders.add(new ProductOrder(120,"创建1"));
        orders.add(new ProductOrder(121,"创建1"));
        orders.add(new ProductOrder(120,"支付1"));
        orders.add(new ProductOrder(120,"完成1"));
        orders.add(new ProductOrder(121,"支付1"));
        orders.add(new ProductOrder(121,"完成1"));
        orders.add(new ProductOrder(122,"创建1"));
        orders.add(new ProductOrder(122,"支付1"));
        orders.add(new ProductOrder(122,"完成1"));
        return orders;
    }

}
